import { reqShopCartInfo, reqischeckedInfo, reqDeleteInfo } from '@/api';

export default {
    state: {
        shopCartList: []
    },
    actions: {
        //获取购物车列表
        async getShopCartList({ commit }) {
            let result = await reqShopCartInfo();
            if (result.code === 200) {
                commit('GETSHOPCARTLIST', result.data);
            }
        },
        //改变某一商品的勾选状态
        async getShopisChecked({ commit }, { skuId, isChecked }) {
            let result = await reqischeckedInfo(skuId, isChecked);
            if (result.code === 200) {
                return 'ok';
            } else {
                return Promise.reject(new Error('faile'));
            }
        },
        //删除某一商品
        async getDelete({ commit }, skuId) {
            let result = await reqDeleteInfo(skuId);
            if (result.code === 200) {
                return 'ok';
            } else {
                return Promise.reject(new Error('faile'));
            }
        },
        //改变所有商品的勾选状态
        updateAllChecked({ dispatch, getters: { cartInfoLists } }, isChecked) {
            let promiseAll = [];
            cartInfoLists.cartInfoList.forEach(item => {
                let promise = dispatch('getShopisChecked', { skuId: item.skuId, isChecked });
                promiseAll.push(promise);
            });
            return Promise.all(promiseAll);
        },
        //删除选中的所有商品
        deleteAllChecked({ dispatch, getters: { cartInfoLists } }) {
            let promiseAll = [];
            cartInfoLists.cartInfoList.forEach(item => {
                let promise = item.isChecked === 1 ? dispatch('getDelete', item.skuId) : '';
                promiseAll.push(promise);
            });
            return Promise.all(promiseAll);
        }
    },
    mutations: {
        GETSHOPCARTLIST(state, shopCartList) {
            state.shopCartList = shopCartList;
        }
    },
    getters: {
        cartInfoLists(state) {
            return state.shopCartList[0] || {}
        }
    }
}